//
//  MatchModel.m
//  Mahjong
//
//  Created by 饶首建 on 17/5/22.
//  Copyright © 2017年 com.ikamobile.com. All rights reserved.
//

#import "MatchModel.h"

@implementation MatchModel

+(void)findOneMatchSuccess:(LoadMatchSuccess)success fail:(LoadMatchFail)fail{
    NSString *url = [BASE_URL stringByAppendingPathComponent:API_GET_MATCH];
    [HttpUtil sendRequestURL:url method:GET param:nil success:^(id response) {
        NSDictionary *dic = response;
        MatchModel *mm = [MatchModel parseDic:dic];
        success(mm);
    } fail:^(NSString *errorStr) {
        fail(errorStr);
    }];
}

+(void)findMatchByGameId:(NSString *)gameId success:(LoadMatchSuccess)success fail:(LoadMatchFail)fail{
    NSString *url = [BASE_URL stringByAppendingPathComponent:NSStringFormat(@"Games/%@/match",gameId)];
    [HttpUtil sendRequestURL:url method:GET param:nil success:^(id response) {
        MatchModel *mm = [MatchModel parseDic:response];
        success(mm);
    } fail:^(NSString *errorStr) {
        fail(errorStr);
    }];
}

+ (MatchModel*)parseDic:(NSDictionary*)dic{
    MatchModel *mm = [MatchModel new];
    mm.matchId = dic[@"id"];
    mm.base = [dic[@"base"]integerValue];
    mm.ceiling = [dic[@"ceiling"] integerValue];
    mm.isSeted = [dic[@"isSeted"]boolValue];
    
    mm.matchCode = dic[@"matchCode"];
    mm.startDate = dic[@"startDate"];

    mm.me = [PlayerModel parse:dic[@"me"]];
    
    NSString *playerId = [PlayerModel ownerInstance].playerId;
    
    NSMutableArray *playersArr = [NSMutableArray new];
    NSMutableArray *othersArr = [NSMutableArray new];
    for (NSDictionary *d in dic[@"_players"]) {
        PlayerModel *pm = [PlayerModel parse:d];
        if (![pm.playerId isEqualToString:playerId] && othersArr.count < 3) {
            [othersArr addObject:pm];
        }
        //限制人数为4
        if (playersArr.count<4) {
            [playersArr addObject:pm];
        }
    }
    mm.players = playersArr;
    mm.others = othersArr;
    mm.rules = dic[@"rules"];
    mm.optionalArr = dic[@"optionalPatterns"];
    return mm;
}

@end
